#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2020/9/24 0024 8:17
# @Email : gxfana.2019@gmail.com
import re
from django import forms
from book import models
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.forms import widgets


# 注册form组件
class Reg(forms.Form):
    username = forms.CharField(label="用户名")
    password = forms.CharField(label="密  码", min_length=6, widget=widgets.PasswordInput(),
                               error_messages={"min_length": "密码不能小于6位", "required": "不能为空!"})
    var_pwd = forms.CharField(label="确认密码", min_length=6, widget=widgets.PasswordInput(),
                              error_messages={"min_length": "密码不能小于6位", "required": "不能为空!"})
    email = forms.CharField(label="邮  箱", min_length=5, widget=widgets.EmailInput(),
                            error_messages={"min_length": "邮箱不符合要求", "required": "不能为空!"})

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for foo in self.fields.values():
    #         foo.widget.attrs.update({"class": "form-control"})  # 为每个字段加个class属性
    #         foo.error_messages = {"required": "不能为空!"}  # 添加共用字段

    def clean_username(self):
        val = self.cleaned_data.get("username")
        user = models.User.objects.filter(username=val).first()
        if user:
            raise ValidationError("用户名已存在")
        else:
            return val

    def clean_password(self):
        val = self.cleaned_data.get("password")
        if val.isdigit():
            raise ValidationError("密码不能是纯数字")
        else:
            return val

    def clean_email(self):
        val = self.cleaned_data.get("email")
        email = models.User.objects.filter(email=val).first()
        if re.search("[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?", val):
            if email:
                raise ValidationError("邮箱已存在")
            else:
                return val
        else:
            raise ValidationError("邮箱格式错误")

    def clean(self):
        pwd = self.cleaned_data.get("password")
        r_pwd = self.cleaned_data.get("var_pwd")
        if pwd and r_pwd and pwd != r_pwd:
            self.add_error("var_pwd", ValidationError("两次密码不一致！"))
        else:
            return self.cleaned_data


# 登陆form组件
class Login(forms.Form):
    username = forms.CharField(label="用户名")
    password = forms.CharField(label="密  码", widget=widgets.PasswordInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for foo in self.fields.values():
            # foo.widget.attrs.update({"class": "form-control"})  # 为每个字段加个class属性
            foo.error_messages = {"required": "不能为空!"}  # 添加共用字段


# 添加书籍form组件
class Book(forms.Form):
    title = forms.CharField(label="书名", max_length=32)  # 书名
    price = forms.IntegerField(label="价格")  # 价格 小数保留后2位
    pub_date = forms.DateField(label="出版日期", widget=widgets.TextInput(attrs={"type": "date"}))  # 出版日期 日期格式
    publish = forms.ModelChoiceField(label="出版社", queryset=models.Publish.objects.all())
    authors = forms.ModelMultipleChoiceField(label="作者", queryset=models.Author.objects.all())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})


# 编辑书籍
class EditBook(forms.ModelForm):
    class Meta:
        model = models.Book
        fields = "__all__"
        labels = {"title": "书名", "price": "价格", "pub_date": "出版日期", "publish": "出版社", "authors": "作者"}
        widgets = {"pub_date": widgets.TextInput(attrs={"type": "date"})}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})


def mobile_validate(value):     # 手机号码校验参考：https://www.cnblogs.com/zhaopanpan/p/9010598.html
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')


class AddAuthor(forms.Form):
    name = forms.CharField(label="姓名")  # 姓名
    sex = forms.ChoiceField(label="性别", choices=((0, "女"), (1, "男"),))
    mobile_tel = forms.CharField(label="手机号码", min_length=11, validators=[mobile_validate],
                                 widget=widgets.TextInput())  # 手机号码
    email = forms.EmailField(label="邮箱")  # 邮箱格式
    addr = forms.CharField(label="联系地址")  # 联系地址

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})


class EditAuthor(forms.ModelForm):
    class Meta:
        model = models.Author
        fields = ["name"]
        labels = {"name": "姓名"}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})


class AuthorDetail(forms.ModelForm):
    class Meta:
        model = models.AuthorDetail
        fields = "__all__"
        labels = {"sex": "性别", "mobile_tel": "手机号码", "email": "邮箱", "addr": "地址"}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})


class Publish(forms.ModelForm):
    class Meta:
        model = models.Publish
        fields = "__all__"
        labels = {"name": "出版社", "city": "地址"}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            filed.widget.attrs.update({"class": "form-control"})